import { api_shop_seller, api_goods_goods_list } from "@/apis/shop";

const state = {
	shopData: {},
	goodsList: [],
};
const getters = {
	// 得到商品类名组合的数组
	navList(state) {
		return state.goodsList.map((v) => v.name);
	},
	//   筛选出count>0的商品列表
	filterGoodsList(state) {
		let temp = [];
		state.goodsList.forEach((v) => {
			v.foods.forEach((item) => {
				if (item.count > 0) {
					temp.push(item);
				}
			});
		});
		return temp;
	},
	// 计算购物车总数量
	filterTotalCount(state, getters) {
		// 第二个参数为计算属性中的所有方法组成的对象，可直接使用
		// console.log(getters);
		return getters.filterGoodsList.reduce((total, cur) => {
			return total + cur.count;
		}, 0);
	},
	// 计算购物车总金额
	filterTotalMoney(state, getters) {
		return getters.filterGoodsList.reduce((total, cur) => {
			return total + cur.count * cur.price;
		}, 0);
	},
};
const mutations = {
	GET_SHOP(state, data) {
		state.shopData = data;
	},
	GET_GOODS_LIST(state, data) {
		state.goodsList = data;
	},
	SET_CLEAR_GOODS(state){
		state.goodsList.forEach(v=>{
			v.foods.forEach(item=>{
				item.count=0
			})
		})
	}
};
const actions = {
	// 获取店铺信息
	$_getShopData({ commit }) {
		new Promise(async (resolve) => {
			const res = await api_shop_seller();
			commit("GET_SHOP", res.data.data);
			// console.log(res);
			resolve();
		});
	},
	// 获取商品列表
	$_getGoodsList({ commit }) {
		new Promise(async (resolve) => {
			const res = await api_goods_goods_list();
			// console.log(res);
			let { code, data } = res.data;
			if (code == 0) {
				data.forEach((v) => {
					v.foods.forEach((item) => {
						item.count = 0;
					});
				});
				commit("GET_GOODS_LIST", data);
				resolve();
			}
		});
	},
};

export default {
	namespaced: true,
	state,
	mutations,
	actions,
	getters,
};
